package cn.my;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * Gitee文件上传工具类
 *
 * @author Sun.Q
 * @since 九月, 30 2021
 */
public class Gitee {

    public static final String ACCESS_TOKEN = "b6b9e0f4584a0832f28b2f24084e9aa6";

    private static final Logger LOGGER = LoggerFactory.getLogger(Gitee.class);

    /**
     * 压缩图片并上传
     *
     * @param bufferedImage 图片流
     * @return 文件连接
     */
    public static Result upImg(BufferedImage bufferedImage) {

        File source = FileUtil.file("/tmp/temp.png");
        try {
            ImageIO.write(bufferedImage, "png", source);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.err(e.getMessage());
        }

        File target = FileUtil.file("/tmp/temp.jpg");

        ImgUtil.convert(source,target);

        return upFile(max(source, target));
    }

    public static File max(File a, File b) {
        return FileUtil.size(a) > FileUtil.size(b) ? b : a;
    }

    /**
     * 上传普通文件
     *
     * @param file 文件
     * @return 文件链接
     */
    public static Result upFile(File file) {

        String path = DateUtil.format(LocalDateTime.now(), "yyyyMM") + "/"
                + DateUtil.format(LocalDateTime.now(), "dd-HH-mm-ss.") + StrUtil.subAfter(file.getName(), ".", true);

        String url = "https://gitee.com/api/v5/repos/xnn9200/img/contents/";

        path = URLEncodeUtil.encode(path);

        JSONObject parms = new JSONObject();

        parms.set("access_token", ACCESS_TOKEN);

        parms.set("content", Base64.encode(file));

        parms.set("message", "add file");

        try {

            String out = HttpUtil.post(url + path, parms);

            LOGGER.info(out);

            JSONObject resultJSON = JSONUtil.parseObj(out);

            if (resultJSON.containsKey("messages")) return Result.err(resultJSON.get("messages").toString());

            JSONObject contentObj = resultJSON.getJSONObject("content");

            String sha = contentObj.getStr("sha");

            path = contentObj.getStr("path");

            String downloadUrl = contentObj.getStr("download_url");

            return Result.succ(downloadUrl, sha, path);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(e.toString());

        }
    }

    public static Result delFile(String path) {

        path = URLEncodeUtil.encode(path);

        String url = "https://gitee.com/api/v5/repos/xnn9200/img/contents/";

        JSONObject parms = new JSONObject();

        parms.set("access_token", ACCESS_TOKEN);

        Result shaResult = getSha(path);

        if (!shaResult.isSuccess()) return shaResult;

        parms.set("sha", shaResult.getSha());

        parms.set("message", "delete last file");

        try {

            String out = HttpUtil.createRequest(Method.DELETE, url + path + "?" + HttpUtil.toParams(parms)).execute().body();

            LOGGER.info(out);

            JSONObject resultJSON = JSONUtil.parseObj(out);

            if (resultJSON.containsKey("messages")) return Result.err(resultJSON.get("messages").toString());

            return Result.delSucc();

        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(e.toString());
        }
    }

    private static Result getSha(String path) {

        String url = "https://gitee.com/api/v5/repos/xnn9200/img/contents/";

        JSONObject parms = new JSONObject();

        parms.set("access_token", ACCESS_TOKEN);

        try {

            String out = HttpUtil.get(url + path + "?" + HttpUtil.toParams(parms));

            LOGGER.info(out);

            if(JSONUtil.isJsonArray(out)) return Result.err("文件不存在");

            JSONObject resultJSON = JSONUtil.parseObj(out);

            String sha = resultJSON.getStr("sha");

            if (resultJSON.containsKey("messages")) return Result.err(resultJSON.get("messages").toString());

            return Result.succ(null, sha, null);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.err(e.toString());

        }
    }

    public static void main(String[] args) {
        //String testFile = "https://res.hc-cdn.com/cpage-pep-home-page/2.0.3/components/customers/images/logo-m1.png";
        //Result result = addImg(ImgUtil.read(testFile));
        //System.out.println("result = " + result);
    }

}
